from typing import Any, Optional, Dict
from pubsub import pub
from src.core.network_manage import NetworkManage
from src.log.logger import setup_logger
from dataclasses import is_dataclass, fields

from src.routing.routing_table import RoutingTable
from src.rpc.KRPC import KRPC
import schedule
import asyncio

class GlobalManage:
    """全局变量管理类（单例模式）
    
    用于管理全局共享的资源和状态，使用字典存储多个网络管理器实例
    """
    _instance: Optional['GlobalManage'] = None  # 单例实例
    
    def __new__(cls):
        """创建或返回单例实例"""
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.logger = setup_logger('globals.globals')
            # 初始化实例属性
            cls._instance.pub = pub
            cls._instance.network_manages = {}
            cls._instance.krpc_manages = {}
            cls._instance.schedule = schedule.Scheduler()
            cls._instance.routing_table = {}
        return cls._instance
    
    @classmethod
    def get_instance(cls) -> 'GlobalManage':
        """获取GlobalManage的单例实例
        
        Returns:
            GlobalManage: 单例实例
        """
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance
    
    
    def publish_event(self, event: Any) -> None:
        """发布事件"""
        if not is_dataclass(event):
            raise ValueError("事件对象必须是 dataclass")
            
        if not hasattr(event, 'topic'):
            raise ValueError("事件对象必须包含 topic 属性")
            
        self.logger.debug(f"正在发布事件: {event.topic}-{event}")

        # 发布事件
        self.pub.sendMessage(
            topicName=event.topic,
            event=event
        )
    
    def add_krpc(self, key: str, krpc: KRPC) -> None:
        """添加KRPC实例"""
        self.krpc_manages[key] = krpc

    def get_krpc(self, key: str) -> KRPC:
        """获取KRPC实例"""
        return self.krpc_manages.get(key)
    
    def remove_krpc(self, key: str) -> None:
        """移除KRPC实例"""
        self.krpc_manages.pop(key, None)

    def add_network_manage(self, key: str, network_manage: NetworkManage) -> None:
        """添加网络管理器
        
        Args:
            key: 网络管理器的唯一标识
            network_manage: 网络管理器实例
        """
        self.logger.info(f"添加网络管理器: {key}")
        self.network_manages[key] = network_manage

    def get_network_manage(self, key: str) -> NetworkManage:
        """获取指定的网络管理器
        
        Args:
            key: 网络管理器的唯一标识
        Returns:
            NetworkManage: 对应的网络管理器实例
        """
        return self.network_manages.get(key)

    def remove_network_manage(self, key: str) -> None:
        """移除网络管理器
        
        Args:
            key: 要移除的网络管理器的唯一标识
        """
        self.logger.info(f"移除网络管理器: {key}")
        self.network_manages.pop(key, None)

    async def run_scheduler(self):
        """异步运行调度器"""
        while True:
            self.schedule.run_pending()
            await asyncio.sleep(1)

    def start_scheduler(self):
        """启动异步调度器"""
        asyncio.create_task(self.run_scheduler())

    def stop_scheduler(self):
        """停止异步调度器"""
        self.schedule.clear()
        self.schedule.stop()
    
    def add_routing_table(self, key: str, routing_table: RoutingTable) -> None:
        """添加路由表"""
        self.routing_table[key] = routing_table

    def get_routing_table(self, key: str) -> Optional[RoutingTable]:
        """获取路由表"""
        return self.routing_table.get(key)

    def remove_routing_table(self, key: str) -> None:
        """移除路由表"""
        self.routing_table.pop(key, None)
